package com.example.controller;

import com.example.common.ApiUriTemplates;
import com.example.common.ResultUtil;
import com.example.demo.User;
import com.example.es.doc.BookDoc;
import com.example.es.repository.BookRepository;
import com.example.service.UserService;
import com.example.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;



@Slf4j
@RestController
@Api(value = ApiUriTemplates.APP_ROOT_PATH)
@RequestMapping(ApiUriTemplates.V1 + "/user")
public class UserControler {
    @Autowired
    private UserService userService;
    @Autowired
    private BookRepository bookRepository;


    @GetMapping(value = "/search")
    @ApiOperation(value = "查找用户")
    public ResultVO searchUser(){
        Iterable<BookDoc> all = bookRepository.findAll();
        System.out.println(all);
        return ResultUtil.success(null);
    }

    @PostMapping
    @ApiOperation(value = "新增用户")
    public ResultVO addUser(@RequestBody @Valid User user, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError allError : allErrors) {
                //log.error(allError.getDefaultMessage());
            }
        }
        return ResultUtil.success(user);
    }

    @PutMapping
    @ApiOperation(value = "修改用户")
    public ResultVO modifyUser(@RequestBody @Valid User user, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError allError : allErrors) {
                //log.error(allError.getDefaultMessage());
            }
        }

        return ResultUtil.success(user);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "查找一个用户")
    public ResultVO getUser(@PathVariable("id") Integer id){
        userService.selectUser("dd");
        return ResultUtil.success();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除一个用户")
    public ResultVO deleteUser(@PathVariable("id") Integer id){

        return ResultUtil.success();
    }

    @GetMapping("/addlist")
    @ApiOperation(value = "批量insert用户")
    public ResultVO getaddListUser(){
        List<User> list = new ArrayList<>();
        for(int i = 0;i<3;i++){
            User user = new User();
            user.setAge(18);
            user.setIdNumber(12344798+"");
            user.setBirthday(new Date());
            user.setUserName("sdf");
            list.add(user);
        }
        userService.insertList(list);
        return ResultUtil.success();
    }
}

